import Vue from 'vue';
import Vuex from 'vuex';
import { Toast } from 'mint-ui'
import  axios  from 'axios'
Vue.use(Vuex);

let rootApi;

if (process.env.NODE_ENV == "development") {
  rootApi = "/api/";
} else {
  rootApi = "http://www.fetail.com/";
}
export const store = new Vuex.Store({
  state: {
    rootApi,
    goodInfo: {},
    access_token: '',
    curTarget: null,
    isShow: {
      remark: false,
      loading: true,
      order:false
    },
    seller:{},
    selectFoods: [],
    store_id: '',
    desk_id: ''
  },
  getters: {
    selectedFoods: function (state) {
      let selectedFoods = [];

      for(let food of state.selectFoods){
        if(food.qty > 0){
          selectedFoods.push(food)
        }
      }
      console.log('change from vuex')
      return selectedFoods;
    }
  },
  mutations: {
    // add cart 
    addCart(state, food) {
      if (state.selectFoods.length === 0) {
        state.selectFoods.push(food)
      } else {
        let isAdd = false;
        for (let item of state.selectFoods) {
          if (item.id === food.id && item.cart_id === food.cart_id) {
            item.qty += 1;
            isAdd = true;
          }
        }
        // 如果没有相同id的，就作为一个新的foodpush进去
        if (!isAdd) {
          state.selectFoods.push(food);
        }
      }
      console.log('selelct food is ==============');
      console.log(state.selectFoods);
      console.log('selelct food is ==============');
    },
    setSeller(state, seller) {
      state.seller = seller;
    },
    setGoodInfo(state, goodInfo) {
      state.goodInfo = goodInfo;
    },
    setAccess_token(state, access_token) {
      state.access_token = access_token;
    },
    setTarget(state, target) {
      state.target = target;
      console.log(state.isShow)
    },
    setShow(state, obj) {
      state.isShow[obj.target] = obj.status;
    },
    clearSelectFoods(state){
      state.selectFoods = []
    },
    loadCacheFood(state){
      if(localStorage.selectFoods){
        state.selectFoods = JSON.parse(localStorage.selectFoods)
      }
    }
  },
  actions:{
    commit(context,data){
      axios.post('/api2/checkout/confirm/order',data.data)
        .then(res => {
          if(res.data.code === 1){
            showToast('success')
            context.commit("setShow", { target: "order", status: false });
            context.commit('clearSelectFoods')
            data.reset()
          }else{
            showToast(res.data.message)
          }
        })
    }
  }
})

console.log(store)
store.watch(
  state => {
    let selectedFoods = [];

      for(let food of state.selectFoods){
        if(food.qty > 0){
          selectedFoods.push(food)
        }
      }
      return selectedFoods;
  },
saveSelectedFood)

function showToast(message){
  Toast({
    message:message,
    duration:2000
  })
}


function saveSelectedFood(){
  localStorage.selectFoods = JSON.stringify(store.getters.selectedFoods)
}

